#include "authorizationCommand.h"

QDomDocument AuthorizationCommand::run(QDomDocument doc) {
    QDomDocument xmlDocument;
    QString result = "<authorization><success>FALSE</success>";
    bool success = false;

    QDomNodeList loginNodes = doc.elementsByTagName("login");
    QDomNodeList passHashNodes = doc.elementsByTagName("passHash");
    if (loginNodes.count() == 1) {
        QString login = loginNodes.at(0).toElement().text().trimmed();

        if (passHashNodes.count() == 1) {
            QString passHash = passHashNodes.at(0).toElement().text().trimmed();
            User* user = DB::getInstance()->findByLogin(login);
            if (user != NULL && user->getPassHash().compare(passHash) == 0) {
                result = "<authorization><success>TRUE</success><identify>";
                result.append(user->getIdentify());
                result.append("</identify></authorization>");
                success = true;
            } else {
                result.append("<reason>NOT_AUTHORIZED</reason>");
            }
        } else {
            User* user = DB::getInstance()->findByLogin(login);
            if (user == NULL) {
                user = new User(login);
                DB::getInstance()->addUser(user);
                result = "<authorization><success>TRUE</success><identify>";
                result.append(user->getIdentify());
                result.append("</identify></authorization>");
            } else {
                result.append("<reason>LOGIN_ALREADY_USED</reason>");
            }
        }

    } else {
        result.append("<reason>WRONG_XML</reason>");
    }

    if (!success) {
        result.append("</authorization>");
    }

    xmlDocument.setContent(result);
    return xmlDocument;
}
